package com.liqi.frame.comm.controller.unit;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.liqi.frame.comm.dto.HttpResult;
import com.liqi.frame.comm.enums.ResultEnum;
import com.liqi.frame.comm.properties.QiniuProperties;
import com.liqi.frame.comm.util.IdUtil;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @author liqi on 2019/10/15 0015. liqiwork@qq.com
 */
@RestController
@RequestMapping("/unit/ajax")
public class UnitAjaxController {
    // ******的内容需要查看七牛云账号的相关信息
//    private static final String accessKey = "DfPO1v9CtfTL3F1QGUpIQyVBXjTcA0EQSKytdkEM";    //访问秘钥
//    private static final String secretKey = "PLk9Jj2HqK492_cZSZewabSJ-3xNLg5N7Hb2RTdZ";    //授权秘钥
//    private static final String bucket = "liqiwork";       //存储空间名称
//    private static final String domain = "http://pzcrxgycy.bkt.clouddn.com";       //外链域名

    @Autowired
    private QiniuProperties qiniuProperties;

    @RequestMapping("/qiniuSimulate4Upload")
    public HttpResult qiniuSimulate4Upload(MultipartFile[] multipleFile, HttpServletRequest request) {
        System.out.println(multipleFile.length);
        return new HttpResult(ResultEnum.SUCCESS);
    }

    /**
     * 七牛云上传生成凭证
     *
     * @throws Exception
     */
    @RequestMapping("/qiniuUpToken")
    public Map<String, Object> qiniuUpToken(@RequestBody Map params)throws Exception  {
        String suffix = params.get("suffix")+"";
        String filePrefix = params.get("filePrefix")+"";
        String fileName = params.get("fileName")+"";

        Map<String, Object> result = new HashMap<String, Object>();
        try {
            //验证七牛云身份是否通过
            Auth auth = Auth.create(qiniuProperties.getAccessKey(), qiniuProperties.getSecretKey());
            //生成凭证
            String upToken = "";
            String randomFileName = "";
            if (StrUtil.isNotEmpty(fileName)) {
                String fileKey = filePrefix+fileName;
                upToken = auth.uploadToken(qiniuProperties.getPublicBucket(), fileKey);
                randomFileName = fileKey;
            } else {
                upToken = auth.uploadToken(qiniuProperties.getPublicBucket());
                //生成实际路径名
                if (StrUtil.isNotEmpty(filePrefix)) {
                    randomFileName = filePrefix + UUID.randomUUID().toString() + suffix;
                } else {
                    randomFileName = UUID.randomUUID().toString() + suffix;
                }
            }
            result.put("fileKey", randomFileName);
            result.put("token", upToken);
            //存入外链默认域名，用于拼接完整的资源外链路径
            result.put("domain", qiniuProperties.getDomain());

            result.put("success", ResultEnum.SUCCESS.getCode());

            result.put("success", ResultEnum.SUCCESS.getCode());
        } catch (Exception e) {
            result.put("message", "获取凭证失败，" + e.getMessage());
            result.put("success", 0);
        } finally {
            return result;
        }
    }

    /**
     * 删除文件
     * @param key 文件的key
     */
    @RequestMapping("/qiniuDeleteByKey")
    public HttpResult qiniuDeleteByKey(@RequestBody Map params) {
        String key = params.get("key")+"";

        Configuration cfg = new Configuration(Zone.huanan());
        Auth auth = Auth.create(qiniuProperties.getAccessKey(), qiniuProperties.getSecretKey());
        BucketManager bucketManager = new BucketManager(auth, cfg);
        try {
            bucketManager.delete(qiniuProperties.getPublicBucket(), key);
        } catch (QiniuException ex) {
            //如果遇到异常，说明删除失败
            System.err.println(ex.code());
            System.err.println(ex.response.toString());
        }

        return new HttpResult(ResultEnum.SUCCESS);
    }

    /**
     * 用后台方法上传到七牛云
     * @param files
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "upload", method = {RequestMethod.POST})
    @ResponseBody
    public HttpResult uploadFile(@RequestParam(value = "file") MultipartFile[] files, HttpServletRequest request) throws Exception {
        Auth auth = Auth.create(qiniuProperties.getAccessKey(), qiniuProperties.getSecretKey());
        String upToken = auth.uploadToken(qiniuProperties.getPublicBucket());
        Configuration cfg = new Configuration(Zone.huanan());
        UploadManager uploadManager = new UploadManager(cfg);
        JSONArray jsonArray = new JSONArray();
        for (MultipartFile mf : files) {
            String fileId = IdUtil.getId()+"";
            String filePrefix = "smt/";
            File file = multipartFileToFile(mf);
            String[] strArray = file.getName().split("\\.");
            int suffixIndex = strArray.length -1;
            String originFileSuffix = strArray[suffixIndex];
            String fileKey = filePrefix+fileId+"."+originFileSuffix;
            Response response = uploadManager.put(file, fileKey, upToken);
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("fileId", fileId);
            jsonObject.put("fileUrl", qiniuProperties.getDomain()+"/"+fileKey);
            jsonArray.add(jsonObject);
        }
        return HttpResult.success(jsonArray);
    }
    private File multipartFileToFile( MultipartFile file ) throws Exception {
        File toFile = null;
        if(file.equals("")||file.getSize()<=0){
            file = null;
        }else {
            InputStream ins = null;
            ins = file.getInputStream();
            toFile = new File(file.getOriginalFilename());
            inputStreamToFile(ins, toFile);
            ins.close();
        }
        return toFile;
    }
    private void inputStreamToFile(InputStream ins, File file) {
        try {
            OutputStream os = new FileOutputStream(file);
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            ins.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
